//
//  ExampleDetailViewController.m
//  NekaPrice
//
//  Created by yu on 2018/6/27.
//  Copyright © 2018年 ma c. All rights reserved.
//

#import "ExampleDetailViewController.h"
#import "ExampleDetailCell.h"
#import "ExampleTypeViewController.h"
#import <JSHAREService.h>
#import <YBImageBrowser.h>
static CGFloat kCellHeight = 300;
@interface ExampleDetailViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableView;

@property (nonatomic, strong)UIView *topView;
@property (nonatomic, strong)UILabel *detailTitleLabel;
@property (nonatomic, strong)UIButton *typeNameButton;

@property (nonatomic, strong)NSArray *shareTypes;
@end



@implementation ExampleDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = _exampleModel.title;
    [self.customBar showBackBtn:YES closeBtn:NO shareBtn:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:YES];
    [self.contentView addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.customBar.height);
        make.left.right.bottom.mas_equalTo(0);
    }];
    
    [self.tableView addSubview:self.topView];
    [self loadData];
}

- (void)loadData {
    
    [self.detailVM requestExampleDetailData:_exampleModel.url finishedBlock:^{
        self.detailTitleLabel.text = self.detailVM.detailModol.title;
        [self setTypeName:self.detailVM.detailModol.typename];
        [self.tableView reloadData];
    }];
    
}





- (ExampleDetailViewModel *)detailVM {
    if (_detailVM == nil) {
        _detailVM = [[ExampleDetailViewModel alloc] init];
    }
    return _detailVM;
}


- (UITableView *)tableView {
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] init];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.contentInset = UIEdgeInsetsMake(80, 0, 10, 0);
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.showsVerticalScrollIndicator = NO;
        [_tableView registerClass:[ExampleDetailCell class] forCellReuseIdentifier:@"cell"];
    }
    return _tableView;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (self.detailVM.detailModol) {
        return [self.detailVM.detailModol.body count];
    }
    return 0;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ExampleDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString *imgURLString = [NSString stringWithFormat:@"%@%@", BASE_URL, self.detailVM.detailModol.body[indexPath.row]];
    NSLog(@"%@", imgURLString);
    [cell setImageURL:imgURLString];
    cell.imgView.frame = CGRectMake(5, 5, K_WIDTH - 10, kCellHeight - 10);
    cell.tapBlock = ^(UIImageView *imageView) {
        YBImageBrowser *browser = [YBImageBrowser new];
        NSMutableArray *tempArr = [NSMutableArray new];
//        for (NSString *imgURL in self.detailVM.detailModol.body) {
//            YBImageBrowserModel *model = [YBImageBrowserModel new];
//            [model setUrlWithDownloadInAdvance:[NSURL URLWithString:FormURL(imgURL)]];
//            YBImageBrowserModel *previewModel = [YBImageBrowserModel new];
//            [previewModel setImageWithFileName:@"yangbanjing" fileType:@"png"];
//            [model setPreviewModel:previewModel];
//            [tempArr addObject:model];
//        }
//        browser.dataArray = tempArr;
//        browser.currentIndex = indexPath.row;
//        [browser show];
    };
    return cell;
    
}






- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return self.tableView.width * 0.66;
}

- (UIView *)topView {
    if (_topView == nil) {
        CGFloat width = kIsiPad ? kContentView_WIDTH : K_WIDTH;
        _topView = [[UIView alloc] initWithFrame:CGRectMake(0, -80, width, 80)];
        [_topView addSubview:self.detailTitleLabel];
        [_topView addSubview:self.typeNameButton];
        
        [self.typeNameButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.mas_equalTo(10);
            make.height.mas_equalTo(30);
            make.width.mas_equalTo(50);
        }];
        
        [self.detailTitleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(50);
            make.left.right.mas_equalTo(0);
            make.height.mas_equalTo(20);
        }];
        
        
    }
    return _topView;
}


- (UILabel *)detailTitleLabel {
    if (_detailTitleLabel == nil) {
        _detailTitleLabel = [[UILabel alloc] init];
        _detailTitleLabel.textAlignment = NSTextAlignmentCenter;
        _detailTitleLabel.font = [UIFont boldSystemFontOfSize:16];
    }
    return _detailTitleLabel;
}

- (UIButton *)typeNameButton {
    if (_typeNameButton == nil) {
        _typeNameButton = [[UIButton alloc] init];
        _typeNameButton.layer.borderWidth = 1;
        _typeNameButton.layer.borderColor = [UIColor lightGrayColor].CGColor;
        _typeNameButton.titleLabel.font = [UIFont systemFontOfSize:14];
        [_typeNameButton setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        [_typeNameButton addTarget:self action:@selector(moreExample:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _typeNameButton;
}

- (void)setTypeName:(NSString *)typeName {
    CGFloat width = [typeName widthWithFixedHeight:30 andEdgeInsets:UIEdgeInsetsMake(0, 5, 0, 5) attributes:@{NSFontAttributeName: [UIFont systemFontOfSize:14]}];
    [self.typeNameButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.width.mas_equalTo(width);
    }];
    [self.typeNameButton setTitle:typeName forState:UIControlStateNormal];
    
}


- (void)moreExample:(UIButton *)btn {
    ExampleTypeViewController *exampleTypeVC = [[ExampleTypeViewController alloc] init];
    exampleTypeVC.title = self.detailVM.detailModol.typename;
    exampleTypeVC.typeURL = self.detailVM.detailModol.type_url;
    __weak typeof(self) weakSelf = self;
    exampleTypeVC.selectedBlock = ^(ExampleModel *model) {
        weakSelf.exampleModel = model;
        [weakSelf loadData];
    };
    [self.navigationController pushViewController:exampleTypeVC animated:YES];
}


- (void)customeNavigationBar:(CustomeNavigationBar *)bar clickShareBtn:(UIButton *)shareBtn {
    NSLog(@"分享");
    [self shareAction];
}


#pragma mark -- 分享
- (void)shareAction {
 
    _shareTypes = @[@{@"title": @"微信好友",
                      @"image": @"wechat",
                      @"type": @(JSHAREPlatformWechatSession)},
                    @{@"title": @"微信朋友圈",
                      @"image": @"wechat_moment",
                      @"type": @(JSHAREPlatformWechatTimeLine)},
                    @{@"title": @"微信收藏",
                      @"image": @"wechat_fav",
                      @"type": @(JSHAREPlatformWechatFavourite)},
                    @{@"title": @"QQ好友",
                      @"image": @"qq",
                      @"type": @(JSHAREPlatformQQ)},
                    @{@"title": @"QQ空间",
                      @"image": @"qzone",
                      @"type": @(JSHAREPlatformQzone)},
                    @{@"title": @"新浪微博",
                      @"image": @"weibo",
                      @"type": @(JSHAREPlatformSinaWeibo)}];
    
    UIAlertController *alert = [[UIAlertController alloc] init];
    alert.popoverPresentationController.sourceView = self.view;
    alert.popoverPresentationController.sourceRect = CGRectMake(K_WIDTH / 2, K_HEIGHT,1.0,1.0);
    for (int i = 0; i < _shareTypes.count; i++) {
        NSString *title = _shareTypes[i][@"title"];
        UIAlertAction *action = [UIAlertAction actionWithTitle:title style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self shareWithIndex:i];
        }];
        [alert addAction:action];
    }
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
    
}




- (void)shareWithIndex:(NSInteger)index {
    JSHAREMessage *message = [JSHAREMessage message];
    NSString *p = _shareTypes[index][@"type"];
    JSHAREPlatform platform = [p integerValue];
    if (platform == JSHAREPlatformSinaWeibo) {
        if (![JSHAREService isSinaWeiBoInstalled]) {
            [MBProgressHUD showError:@"未安装新浪微博客户端" toView:self.view];
            return;
        }
    }else if (platform == JSHAREPlatformWechatSession || platform == JSHAREPlatformWechatFavourite || platform == JSHAREPlatformWechatTimeLine) {
        if (![JSHAREService isWeChatInstalled]) {
            [MBProgressHUD showError:@"未安装微信客户端" toView:self.view];
            return;
        }
    }else if (platform == JSHAREPlatformQQ || platform == JSHAREPlatformQzone) {
        if (![JSHAREService isQQInstalled]) {
            [MBProgressHUD showError:@"未安装QQ客户端" toView:self.view];
            return;
        }
    }
    
    message.platform = platform;
    message.mediaType = JSHARELink;
    message.url = [NSString stringWithFormat:@"%@/m/view.php?aid=%@", BASE_URL, self.detailVM.detailModol.id];
//    message.text = self.detailVM.detailModol.title;
    message.title = self.detailVM.detailModol.title;
    
    NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:FormURL(self.exampleModel.litpic)]];
    message.image = imageData;
    
    [JSHAREService share:message handler:^(JSHAREState state, NSError *error) {
        NSLog(@"%ld---%@", state, error.description);
        NSLog(@"分享回调");
        
    }];
}





@end
